// pages/storer/bouter.js
var app = getApp();
var api = require('../../utils/api.js');
var rsa = require('../../utils/rsa.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsArr: [],
    inputValue: '', //输入框内容
    totalNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //减少-1
  minusAction: function (e) {
    const index = e.currentTarget.dataset.info;
    var arr = this.data.goodsArr;
    var tempdic = arr[index];
    var valu = parseInt(tempdic.amount) - 1;
    if (valu < 0) return;
    tempdic.amount = valu;
    arr.splice(index, 1, tempdic);
    this.setData({
      goodsArr: arr,
    })
  },
  //修改数据 
  bindManual: function (e) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    var goar = this.data.goodsArr;
    var tempdic = goar[index];
    tempdic.amount = value;
    goar.splice(index, 1, tempdic);
    this.setData({
      goodsArr: goar,
    })
  },

  //加+1
  plusAction: function (e) {
    const index = e.currentTarget.dataset.info;
    var arr = this.data.goodsArr;
    var tempdic = arr[index];
    var valu = parseInt(tempdic.amount) + 1;
    tempdic.amount = valu;
    arr.splice(index, 1, tempdic);
    this.setData({
      goodsArr: arr,
    })
  },
  //删除某一列
  deleCellAction: function (e) {
    var tempArr = this.data.goodsArr;
    const vale = e.currentTarget.dataset.info;
    tempArr.splice(vale, 1);
    this.setData({
      goodsArr: tempArr,
      totalNum: tempArr.length,
    })
  },
  //输入框输入
  bindRcodeInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  //扫描
  scanAction: function () {
    wx.scanCode({
      success: (res) => {
        console.log(res.result);
        this.querygood(res.result);
      }
    })
  },
  //搜索
  searchAction: function () {
    const vale = this.data.inputValue;
    if(vale!=''){
      this.querygood(vale);
    }
  },
  querygood: function (e) {
    const shopnum = app.globalData.shoopnum;
    const setion = app.globalData.session;
    rsa.Cpic_fetchPost(rsa.SERVERPORT, {
      'method': 'goods.keyword', "seller_bn": shopnum, 'session_id': setion, 'keyword': this.data.inputValue
    }, (err, res) => {
      console.log(res);
      var datas = res.data.list;
      if (datas.length == 0) {
        wx.showToast({
          title: '未查询到商品',
          icon: 'none',
          duration: 2000
        })
        return;
      }
      var tempArr = this.data.goodsArr;
      for (var i = 0; i < datas.length; i++) {
        var templist = datas[i];
        var gname = templist.name;
        var numbe = templist.quantity;
        if (!numbe || numbe == '') {
          numbe = '0'
        }
        if (!gname) continue;
        var pri = templist.price;
        var tempArrs = { name: gname, gnum: templist.barcode, price: pri, amount: 0, samount: numbe, num: templist.bn };
        tempArr.push(tempArrs);
      }
      this.setData({
        goodsArr: tempArr,

      })

    })
  },
  //查询商品
  requestGoodsDetail: function (e) {
    const shopnum = app.globalData.shoopnum;
    const settion = app.globalData.session;
    var barcode = '';
    var name = '';
    var reg = /^\d+(\.\d+)?$/;
    if (reg.test(e) == true) {
      console.log('是数字');
      barcode = e;
    } else {
      name = e;
      console.log('不是数字');
    }
    rsa.Cpic_fetchPost(rsa.SERVERPORT, {
      'method': 'goods.search', "seller_bn": shopnum, 'session_id': settion, "cat_id": '', "name": name, "syns_time": '', "barcode": barcode, "page_num": '10', "page": '1'
    }, (err, res) => {
      if (!res || res == '') {
        return
      }
      var redata = res.data.list;
      if (redata.length > 0) {
        var good_detail = redata[0];
        var gooArr = this.data.goodsArr;
        var cprice = parseFloat(good_detail.price).toFixed(2);
        var bnum = good_detail.bn
        var tempArr = { name: good_detail.name, gnum: e, price: cprice, amount: 0, samount: good_detail.store, num: bnum };
        gooArr.splice(0, 0, tempArr);
        var total = gooArr.length;
        this.setData({
          goodsArr: gooArr,
          totalNum: total,
        })
      } else {
        wx.showToast({
          title: '未查询到该商品',
          icon: 'fail',
          duration: 5000
        })
      }
    });
  },
  //重置价格
  resetPrice: function (e) {
    console.log("price:" + e);
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    var goar = this.data.goodsArr;
    var tempdic = goar[index];
    tempdic.price = value;
    goar.splice(index, 1, tempdic);
    this.setData({
      goodsArr: goar,
    })
  },
  getCurrentTime: function () {
    var date = new Date();
    var year = date.getFullYear();
    var m = date.getMonth() + 1;
    var month = m < 10 ? '0' + m : m;
    var day = date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
  },
  //入库操作
  innerAction:function(){
    var gd = this.data.goodsArr;
    if (gd.length == 0) return;
    var ctime = this.getCurrentTime();
    var handle_user = app.globalData.shopName;
    const shopnum = app.globalData.shoopnum;
    var outArr = [];
    // { name: good_detail.product_name, gnum: e, price: cprice, amount: good_detail.store_count, samount: good_detail.store_count };
    for (var i = 0; i < gd.length; i++) {
      var temp = gd[i];
      var pcode = temp.gnum;
      var num = temp.amount;
      var cost = (parseFloat(temp.price) * 100).toFixed(0);
      var bn = temp.num;
      var dic = { "good_bn": bn, "stock": num, "price": cost, "remark": "" };
      outArr.push(dic);
    }
    var that = this;

    const settion = app.globalData.session;
    var that = this;
    rsa.Cpic_fetchPost(rsa.SERVERPORT, { 'method': 'goods.up_store', 'seller_bn': shopnum, 'session_id': settion, 'store_type': 'fastin', "remark": ctime, 'goods_data': outArr }, (err, res) => {
      if (!res || res == '') {
        wx.showToast({
          title: err,
          icon: 'success',
          duration: 2000
        })
        return;
      }
      if (res.return_code == '0000') {
        wx.showModal({
          title: '提示',
          content: res.return_msg,
          showCancel:false,
          success: function (res) {
            that.setData({
              goodsArr: [],
              totalNum: 0,
            })
            if (res.confirm) {
              wx.navigateBack({
                delta: 1
              })

            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      } else {
        wx.showToast({
          title: res.return_msg,
          icon: 'success',
          duration: 2000
        })
      }

    });
  }
})